package org.huangjie.util;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @author Huang Jie
 * @date 2024/05/18
 */
public class Ipv6Utils {

    public static List<String> getLocalIpv6s() {
        List<String> ipv6s = new ArrayList<>();

        Enumeration<NetworkInterface> interfaces;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
        while (interfaces.hasMoreElements())
        {
            NetworkInterface interf = interfaces.nextElement();
            Enumeration<InetAddress> addres = interf.getInetAddresses();
            while (addres.hasMoreElements())
            {
                InetAddress in = addres.nextElement();
                if (in instanceof Inet6Address) {
                    // 排除本地回环地址
                    if (in.getHostAddress().startsWith("fe80:")) {
                        continue;
                    }
                    if (in.getHostAddress().startsWith("2001:")) {
                        continue;
                    }
                    if (in.getHostAddress().startsWith("0:")) {
                        continue;
                    }
                    // 添加到ipv6集合
                    String hostAddress = in.getHostAddress();
                    // linux ipv6地址后面会带有%eth0,需要去掉
                    if (hostAddress.contains("%")){
                        hostAddress = hostAddress.substring(0,hostAddress.indexOf("%"));
                    }
                    ipv6s.add(hostAddress);
                }
            }
        }
        return ipv6s;
    }
}
